// import React from 'react';
import React, {Component} from 'react';

class IndexNewSlider extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            newArr : [
                {
                    link:'http://tech.163.com/18/0110/14/D7Q1PTST00098IEO.html',
                    text:'优必选双足机器人Walker'
                },
                {
                    link:'https://www.toutiao.com/i6507483715910763012/',
                    text:'AI风向标：发改委重大工程项'
                },
                {
                    link:'http://www.sohu.com/a/205103625_465975',
                    text:'优必选荣获TRECVID 2017子任务冠军'
                },
                {
                    link:'http://mp.weixin.qq.com/s/VkFWAymJ-xI7GLZPMxu-ig',
                    text:'优必选斩获 IJCAI 2017最佳学生论文奖'
                }
            ],
            newIndex : 0
        };
        /* 定时器引用 */
        this.timer = null;

        /* 绑定事件中this */
        this.aiNewsList = this.aiNewsList.bind(this);
        this._updateIndex = this._updateIndex.bind(this);
    }
    componentDidMount(){
        this._updateIndex(this.state.newIndex,this.state.newArr.length);
    }
    /**
     * 组件卸载时，清理定时器
     */
    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }
    aiNewsList(arr){
        var newsArr = [];
        for(var i=0;i< arr.length; i++){
            var liClassName = i== this.state.newIndex ? 'ai-slide-top-item new-is-show':'ai-slide-top-item';
            newsArr.push(<li className={liClassName} key={i}><a href={arr[i].link}>{arr[i].text}</a></li>);
        }
        return newsArr;
    }
    _updateIndex(index, len, delay=3000) {
        /* 清除定时器 */
        this.timer && clearInterval(this.timer);
        /* 设置当前展示新闻 */
        this.setState({
            newIndex: index
        });
        /* 打开定时器 */
        this.timer = setInterval(
            () => {
                var currentIndex = this.state.newIndex;
                this.setState({
                    newIndex: (currentIndex + 1) % len
                });
            },
            delay
        );
    }
    render() {
        const newList = this.aiNewsList(this.state.newArr);
        return (
               <div className="ai-index-swipe-news">
                   <div className="ai-swipe-news-title">
                       最新动态
                   </div>
                   <div className="ai-index-new-gun">
                       <ul>
                           {newList}
                       </ul>
                   </div>
                   <a className="ai-index-new-btn" href="#">
                       更多
                   </a>
               </div>
        )}
}
//导出组件
module.exports = IndexNewSlider;